package com.base.common.util;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class HttpUtil {
    public static final String TAG = "HttpUtil";

    static Context context;

    private static boolean isNetworkAvailable(){
        if(null == context){
            Log.e(TAG,"在调用 isNetworkAvailable 方法时，必须传入 context 对象");
            return false;
        }
        if(NetworkAvailableUtils.isNetworkAvailable(context)){
            return true;
        }else{
            Log.e(TAG,"当前设备网络未连接，请检查设备WIFI 或 3/4G 是否打开并能连网！");
            return false;
        }
    }
    /**
     * POST异步提交数据
     */
    public static void post(String url, Map<String,String> params, Callback callback) {
        post(url, null, params, callback);
    }
    /**
     * POST异步提交数据
     */
    public static void post(String url, Map<String,String> head,
                             Map<String,String> params, Callback callback) {
        if(!isNetworkAvailable()) return;
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder=new Request.Builder().url(url);

        JSONObject debugJson = new JSONObject();
        Map<String,String> headMap = new HashMap<>();
        Map<String,String> paramsMap = new HashMap<>();
        debugJson.put("url", url);
        debugJson.put("method", "POST");
        debugJson.put("headers", headMap);
        debugJson.put("params", paramsMap);

        if(head!=null&&head.size()>0){
            for (Map.Entry<String, String> entry : head.entrySet()) {
                String key = entry.getKey();
                String val = entry.getValue();
                headMap.put(key, val);
                builder.addHeader(key,val);
            }
        }

        FormBody.Builder formBody = new FormBody.Builder();
        if(params!=null && params.size()>0){
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String val = entry.getValue();
                paramsMap.put(key, val);
                formBody.add(entry.getKey(),entry.getValue());
            }
        }
        Log.d(TAG, debugJson.toJSONString());
        RequestBody requestBody = formBody.build();
        Request request=builder.post(requestBody).build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * Delete 异步删除数据
     */
    public static void delete(String url, Map<String,String> head,
                           Map<String,String> params, Callback callback) {
        request(url, head, params, callback, "DELETE");
    }

    /**
     * PUT异步修改数据
     */
    public static void put(String url, Map<String,String> params, Callback callback) {
        request(url, null, params, callback, "PUT");
    }

    /**
     * PUT异步修改数据
     */
    public static void put(String url, Map<String,String> head,
                            Map<String,String> params, Callback callback) {
        request(url, head, params, callback, "PUT");
    }

    public static void request(String url, Map<String,String> head,
                               Map<String,String> params, Callback callback, String method){
        if(!isNetworkAvailable()) return;
        if(StringUtils.isEmpty(method) || method.equals("GET")){
            get(url, head, params, callback);
            return;
        }
        JSONObject debugJson = new JSONObject();
        Map<String,String> headMap = new HashMap<>();
        Map<String,String> paramsMap = new HashMap<>();
        debugJson.put("url", url);
        debugJson.put("method", method);
        debugJson.put("headers", headMap);
        debugJson.put("params", paramsMap);
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder=new Request.Builder().url(url);
        if(head!=null&&head.size()>0){
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String val = entry.getValue();
                headMap.put(key, val);
                builder.addHeader(key,val);
            }
        }

        FormBody.Builder formBody = new FormBody.Builder();
        if(params!=null && params.size()>0){
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String val = entry.getValue();
                paramsMap.put(key,val);
                formBody.add(entry.getKey(),entry.getValue());
            }
        }
        Log.d(TAG, debugJson.toJSONString());
        method = method.toUpperCase();
        RequestBody requestBody = formBody.build();
        Request request =  builder.method(method, requestBody).build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * GET 请求数据
     */
    public static void get(String url, Callback callback) {
        get(url, null, null, callback);
    }

    /**
     * GET 请求数据
     */
    public static void getWithHeaders(String url, Map<String,String> head, Callback callback) {
        get(url, head, null, callback);
    }

    /**
     * GET 请求数据
     */
    public static void get(String url, Map<String,String> params, Callback callback) {
        get(url, null, params, callback);
    }
    /**
     * GET 请求数据
     */
    public static void get(String url, Map<String,String> head,
                            Map<String,String> params, Callback callback) {
        if(!isNetworkAvailable()) return;
        OkHttpClient client = new OkHttpClient();
        String gurl = getParsUrl(url, params);
      //  Log.i(TAG, "url="+gurl);

        JSONObject debugJson = new JSONObject();
        Map<String,String> headMap = new HashMap<>();
        Map<String,String> paramsMap = new HashMap<>();
        debugJson.put("url", url);
        debugJson.put("method", "GET");
        debugJson.put("headers", headMap);


        Request.Builder builder=new Request.Builder().url(gurl);
        if(head != null && head.size() > 0){
            for (Map.Entry<String, String> entry : head.entrySet()) {
                String key = entry.getKey();
                String val = entry.getValue();
                headMap.put(key, val);
                builder.addHeader(key,val);
            }
        }
        Log.d(TAG, debugJson.toJSONString());
        Request request=builder.get().build();
        client.newCall(request).enqueue(callback);
    }

    private static String getParsUrl(String url , Map<String, String> params){
        StringBuilder sb = new StringBuilder();
        if(null == params || params.size() == 0) return url;

        Set<String> keys = params.keySet();
        int index = 0;
        for(String key : keys){
            String sign = "&";
            if(index == 0){
                if(url.indexOf("?") == -1){
                    sign = "?";
                }
            }
            String val = params.get(key);
            if(null == val) val = "";
            sb.append(sign).append(key).append("=").append(val);
            index++;
        }
        return url+sb.toString();
    }

    public static void setContext(Context mContext) {
        context = mContext;
    }
}
